<?php
/**
 * Created by PhpStorm.
 * User: 86173
 * Date: 2020-08-20
 * Time: 17:09
 */
require_once "./lib/DB.php";
if(isset($_GET['action'])){
    $dbObj =  new \libs\DB("user");
    $redis = new Redis();
    $redis->connect("127.0.0.1",6379);
    $redis->auth("tangwei");
    switch($_GET['action']){
        case "register"://注册
            //1.接收数据
            $data = $_POST;
            //2.验证数据
             $data = validateData($data);
             $queryRes = $dbObj->where("name",$data['name'],"=")->limit(0,1)->query();
             if(!isset($queryRes["code"])){
                 echo json_encode(["code"=>404,"msg"=>"用户名已存在"]);die;
             }
             //3.处理数据
            $data["password"] = md5($data["password"]);
             $data['inrod'] = htmlspecialchars($data['inrod']);
            $data['create_time'] = date("Y-m-d H:i:s",time());

            $result = $dbObj->insert($data);
            if($result['code'] == 1){
                echo json_encode(["code"=>200,"msg"=>"注册成功"]);
            }else{
                echo json_encode(["code"=>200,"msg"=>"注册失败"]);
            }
        break;
        case "login"://登录
            $data = $_POST;
            if(empty($data['name']) || empty($data["password"])){
                echo json_encode(["code"=>401,"msg"=>"用户名、或密码不能为空"]); die;
            }
            $queryRes = $dbObj->where("name",$data['name'],"=")->limit(0,1)->query();
            if(isset($queryRes["code"])){
                echo json_encode(["code"=>404,"msg"=>"用户名不已存在"]);die;
            }
            $errorCount = $redis->get($data['name']);


            if($errorCount >= 5){
                echo json_encode(["code"=>401,"msg"=>"该用户已被禁用,过一天后在试"]);die;
            }
            $queryRes = $dbObj
                ->where("name",$data['name'])
                ->where("password",md5($data['password']))
                ->limit(0,1)
                ->query();

            if(isset($queryRes["code"])){
                if(empty($errorCount)){
                    $redis->set($data['name'],1,60 * 60 * 24);
                }else{
                    $redis->incr($data['name']);
                }
                echo json_encode(["code"=>404,"msg"=>"密码错误"]);die;
            }
            setcookie("userId",$queryRes[0]["id"],time() + 10 * 60);
            setcookie("userInfo",json_encode($queryRes[0]),time() + 10 * 60);
            echo json_encode(["code"=>200,"msg"=>"登录成功"]);
        break;
        case "add":
            $userId = isLogin();
            $data = $_POST;
            $validateArticle = ["title"=>"标题","content"=>"文章内容"];
            foreach($data as $key=>$value){
                if(empty($data[$key])){
                    echo json_encode(["code"=>401,"msg"=>$validateArticle[$key]."不能为空"]);die;
                }
            }
            $data['content'] = htmlspecialchars($data['content']);
            $data['create_time'] = date("Y-m-d H:i:s",time());
            $data["user_id"] = $userId;
            $result = \libs\DB::table("article")->insert($data);
            if($result['code'] == 1){
                if($redis->exists("hotArticle")){
                    $articleLen = $redis->lLen("hotArticle");
                    if($articleLen >= 10){
                        $redis->rPop("hotArticle");
                    }
                    $redis->lPush("hotArticle",$result['insert_id']);
                }else{
                    $redis->lPush("hotArticle",$result['insert_id']);
                }
                echo json_encode(["code"=>200,"msg"=>"发帖成功"]);
            }else{
                echo json_encode(["code"=>200,"msg"=>"发帖失败"]);
            }
         break;
        case "index":
          $page = $_GET['page'] ?? 1;
          $limit = $_GET['limit'] ?? 2;
          $start = floor($page * $limit - $limit);

          $data = \libs\DB::table("article")
              ->where("status",0,"<>")
              ->limit($start,$limit)
              ->query();
          $userData = \libs\DB::table("user")->query();
          $userName = array_column($userData,'name','id');


          foreach($data as $key=>$value){
              foreach($userName as $k=>$v){
                  if($data[$key]['user_id'] == $k){
                      $data[$key]['name'] =$userName[$k];
                  }
              }
          }
          //  var_dump($data);
          $count= count(\libs\DB::table("article") ->where("status",0,"<>")->query());
         echo json_encode(["code"=>0,"msg"=>"ok","count"=>$count,"data"=>$data]);

        break;
        default:
            echo json_encode(["code"=>401,"msg"=>"非法操作"]);
        break;
    }
}else{
    echo json_encode(["code"=>401,"msg"=>"非法操作"]);
}
/**
 * 验证注册数据
 * @param $data
 * @return mixed
 */
function validateData($data){
    $dataInfo = ["nickname"=>"呢称","name"=>"用户名","password"=>"密码","inrod"=>"用户简介"];
    foreach($data as $key=>$value){
        if(empty($data[$key])){
            echo json_encode(["code"=>401,"msg"=>$dataInfo[$key]."不能为空"]);die;
        }
    }
    return $data;
}

/**
 * 验证用户是否登录
 */
function isLogin(){
    if(!isset($_COOKIE['userId'])){
        echo json_encode(["code"=>401,"msg"=>"用户未登录"]);die;
    }
    return $_COOKIE['userId'];
}